import SearchBtn from '@/components/SearchBtn'
import React, { Component } from 'react'
import Main from './components/Main'
import NavTab from './components/NavTab'
import './style.scss'
import { getCategoryListApi, getMaterialListApi } from '@/api/categoryApi'

class Category extends Component {
  state = {
    // 0 分类，1食材
    navTabCurrentIndex: 0,
    cateData: null,
    menu: [],
    mainData: []
  }
  setNavTabCurrentIndex = navTabCurrentIndex => {
    this.setState({ navTabCurrentIndex }, () => {
      this.loadData()
    })
  }

  componentDidMount() {
    this.loadData()
  }

  loadData = async () => {
    let ret = null
    if (this.state.navTabCurrentIndex === 0) {
      ret = await getCategoryListApi()
    } else {
      ret = await getMaterialListApi()
    }
    this.setState({
      cateData: ret.data,
      menu: Object.keys(ret.data),
      mainData: Object.values(ret.data).shift()
    })
  }

  setMainData = key => {
    this.setState({
      mainData: this.state.cateData[key]
    })
  }

  render() {
    let { navTabCurrentIndex, cateData, mainData, menu } = this.state
    return (
      <div>
        <NavTab currentIndex={navTabCurrentIndex} setNavTabCurrentIndex={this.setNavTabCurrentIndex} />
        <SearchBtn onClick={() => console.log('search')} />
        {/* 
          主体 如果加上一个key,它每次都会重新执行1个新的，所以你的判断全对
          没有加key的话，需要在组件中来判断是否为第1次以后续你进入时，我要操作的动作
        */}
        {/* {cateData != null && <Main key={'cate_' + Date.now()} data={cateData} />} */}
        {cateData != null && <Main navTabCurrentIndex={navTabCurrentIndex} data={cateData} mainData={mainData} menu={menu} setMainData={this.setMainData} />}
      </div>
    )
  }
}

export default Category
